#[macro_use]
extern crate log;
#[macro_use]
extern crate sscanf;

use atport::ATPort;
use atport::Usart;
use std::time::Duration;

fn main() {
    let global_filter =
        tracing_subscriber::EnvFilter::from_default_env().add_directive("debug".parse().unwrap());

    tracing_subscriber::fmt()
        .with_env_filter(global_filter)
        .init();

    info!("Hello, world!");

    let port = serialport::new("/dev/ttyACM0", 9600)
        .data_bits(serialport::DataBits::Eight)
        .stop_bits(serialport::StopBits::One)
        .parity(serialport::Parity::None)
        .flow_control(serialport::FlowControl::None)
        .timeout(Duration::from_millis(1))
        .open()
        .unwrap();

    let mut atport = ATPort::new(Usart::new(port).start_recv(), 128);

    atport.send("AT").unwrap();
    println!(
        "{:?}",
        atport.recv_timeout_equal("OK", Duration::from_millis(1000))
    );

    atport.send("AT").unwrap();
    println!(
        "{:?}",
        atport.recv_timeout_equal("OK", Duration::from_millis(1000))
    );

    atport.send("AT+TEMPERATURE?").unwrap();
    if let Ok(s) = atport.recv_timeout_starts_with("+TEMPERATURE:", Duration::from_millis(100)) {
        println!("temperature: {:?}", sscanf!(s, "+TEMPERATURE:{f64}"));
    }

    loop {
        if let Some(s) = atport.urc_pop() {
            println!("urc: {:?}", s);
        } else {
            std::thread::sleep(Duration::from_millis(100));
        }
    }
}
